package com.wiwl.web.controller;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class RequestController {

	@Secured(value = "ROLE_USER")
	@RequestMapping(value = "/createFiltros")
	public ModelAndView createFiltro() {
		ModelAndView modelView = new ModelAndView();
		return modelView;
	}

	@Secured(value = "ROLE_ADMIN")
	@RequestMapping(value = "/download/{filename}")
	public void download(HttpServletRequest req, HttpServletResponse resp,
			@PathVariable String filename) throws IOException {
		URL folder = this.getClass().getClassLoader().getResource("com");
		filename += ".properties";
		File f = new File(folder.getPath() + filename);
		f.deleteOnExit();
		int length = 0;
		ServletOutputStream op = resp.getOutputStream();

		resp.setContentType("application/octet-stream");
		resp.setContentLength((int) f.length());
		resp.setHeader("Content-Disposition", "attachment; filename=\""
				+ filename + "\"");

		byte[] bbuf = new byte[30];
		DataInputStream in = new DataInputStream(new FileInputStream(f));

		while ((in != null) && ((length = in.read(bbuf)) != -1)) {
			op.write(bbuf, 0, length);
		}

		in.close();
		op.flush();
		op.close();
		f.deleteOnExit();

	}
}
